package com.example.work.controller;

import com.example.work.entity.*;
import com.example.work.entity.vo.AreaScoreVo;
import com.example.work.entity.vo.CategoryScoreVo;
import com.example.work.entity.vo.ItemScoreVo;
import com.example.work.service.*;
import com.example.work.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/hospCheckCategory")
public class HospCheckCategoryController {

    @Autowired
    private ITbHospCheckCategoryService hospCheckCategoryService;

    @Autowired
    private ITbCheckBatchService batchService;

    @Autowired
    private IDbHospService dbHospService;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IAreaService areaService;

    @Autowired
    private ITbCheckAreaScoreService areaScoreService;

    @Autowired
    private ITbCheckItemScoreService itemScoreService;

//    @GetMapping("/page")
//    public R page(@RequestParam(value = "current", defaultValue = "1") int page,
//                  @RequestParam(value = "size", defaultValue = "10") int size){
//        try {
//            // 分页查询区域列表
//            IPage<TbHospCheckCategory> areaPage = hospCheckCategoryService.page(new Page<>(page, size));
//
//            List<TbHospCheckCategory> list = areaPage.getRecords();
//            List<CheckHospBatchVo> resp = new ArrayList<>();
//
//            for(int i = 0; i < list.size(); i++){
//                CheckHospBatchVo vo = CheckHospBatchVo.getCheckHospBatchVo(list.get(i));
//                if(!vo.equals(null)){
//                    vo.setBatchStatus(batchService.getById(vo.getBatchId()).getStatus());
//                    vo.setHospName(dbHospService.getById(vo.getHospId()).getHospName());
//                    vo.setCategoryName(categoryService.getById(vo.getCategoryId()).getName());
//                    resp.add(vo);
//                }
//            }
//
//            // 组装分页结果
//            Map<String, Object> map = new HashMap<>();
//            map.put("records", resp); // 当前页数据
//            map.put("total", areaPage.getTotal()); // 总记录数
//            map.put("pages", areaPage.getPages()); // 总页数
//            map.put("current", areaPage.getCurrent()); // 当前页码
//            map.put("size", areaPage.getSize()); // 每页大小
//
//            return R.ok(map);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return R.error("获取列表失败：" + e.getMessage());
//        }
//
//    }

    /**
     * 根据batch id获取其对应的考核类别打分项
     * **/
    @GetMapping("/batch/{id}")
    public R getBatchHospCheckCategory(@PathVariable String id){

        List<TbHospCheckCategory> categories = hospCheckCategoryService.lambdaQuery().eq(TbHospCheckCategory::getBatchId, id).list();
        if(categories == null || categories.size() == 0)
            return R.error("无法获取批次考核项目");
        Map<String, Object> map = new HashMap<>();
        map.put("records", categories);
        return R.ok(map);
    }

    /**
     * 根据hospCheckCategory获取其下的所有的区域及其项目，将其装饰后返回
     * **/
    @GetMapping("/category/{id}")
    public R getCateGoryItemsVo(@PathVariable String id){


        // 获取hospCheckCategory
        TbHospCheckCategory hospCheckCategory = hospCheckCategoryService.getById(id);

        // 获取category和hosp
        DbCheckCategory category = categoryService.getById(hospCheckCategory.getCategoryId());
        Dbhosp hosp = dbHospService.getById(hospCheckCategory.getHospId());

        // 获取areas
        List<AreaScoreVo> areaScoreVoList = areaScoreService.getAreaScoreVo(category.getId(), hospCheckCategory.getBatchId(),hospCheckCategory.getHospId());

        CategoryScoreVo categoryScoreVo = new CategoryScoreVo();

        categoryScoreVo.setHospCheckCategory(hospCheckCategory);
        categoryScoreVo.setCategoryName(category.getName());
        categoryScoreVo.setHospName(hosp.getHospName());
        categoryScoreVo.setAreas(areaScoreVoList);

        Map<String, Object> map = new HashMap<>();
        map.put("data", categoryScoreVo);

        return R.ok(map);
    }

    /**
     * 检测该考核项目下的已完成考核的区域
     * **/
    @GetMapping("/category/check/{id}")
    public R getCateGoryCheck(@PathVariable String id){
        // 根据categoryId获取
        // 获取hospCheckCategory
        // System.out.println("=== 检查开始 ===");
        TbHospCheckCategory hospCheckCategory = hospCheckCategoryService.getById(id);

        List<TbCheckAreaScore> areaScores = areaScoreService.lambdaQuery()
                .eq(TbCheckAreaScore::getCategoryId, hospCheckCategory.getCategoryId())
                .eq(TbCheckAreaScore::getBatchId, hospCheckCategory.getBatchId())
                .eq(TbCheckAreaScore::getHospId, hospCheckCategory.getHospId())
                .list();
        // System.out.println("检查结果：" + areaScores.size());
        List<String> completedAreas = new ArrayList<>();
        for(TbCheckAreaScore checkAreaScore : areaScores)
            completedAreas.add(checkAreaScore.getAreaId());

        Map<String, Object> map = new HashMap<>();
        map.put("data", completedAreas);
        System.out.println(map);
        return R.ok(map);
    }



    /**
     *
     * 按照区域打分
     **/
    @PostMapping("/score/area")
    @Transactional(rollbackFor = Exception.class)
    public R postAreaScore(@RequestBody AreaScoreVo areaScore){

        if(areaScore == null)
            return R.error("打分内容为空");
        // System.out.println(areaScore.toString());
        try{
            TbCheckAreaScore tbCheckAreaScore = areaScore.getAreaScore();
            if(!areaScoreService.save(areaScore.getAreaScore()))
                throw new Exception();
            // 观察是否有id
            // 如果有id，则设置item的id
            // System.out.println("插入后获取id： " +  tbCheckAreaScore.getId());

            // 插入所有的item score项目
            for(ItemScoreVo itemScore : areaScore.getItems()){
                TbCheckItemScore tbCheckItemScore = itemScore.getItemScore();
                tbCheckItemScore.setAreaScoreId(tbCheckAreaScore.getId());
                // System.out.println(tbCheckItemScore.toString());
                if(!itemScoreService.save(tbCheckItemScore))
                    throw new Exception();
            }
            return R.ok();

        }catch (Exception e){
            e.printStackTrace();
            return R.error(e.getMessage());
        }


    }

    /**
     * 考核项目打分提交
     * 1. 检查项目下面所有的区域是否都已经提交完成
     * 2. 提交，更新该hospCheckCategory的状态
     * 3. 检查批次下面的所有项目是否都已经完成，完成了就更新状态
     * **/
    @GetMapping("/score/category/{id}")
    @Transactional(rollbackFor = Exception.class)
    public R postCategoryScore(@PathVariable String id){
        if(id == null)
            return R.error("提交内容为空");
        // System.out.println("id : " + id);
        // 检查内部区域是否都完成提交了
        TbHospCheckCategory hospCheckCategory = hospCheckCategoryService.getById(id);
        // System.out.println(hospCheckCategory);
        try{
            // 获取categoryScore其下的所有的区域
            List<TbCheckAreaScore> areaScores = areaScoreService.getCategoryArea(hospCheckCategory.getCategoryId(), hospCheckCategory.getBatchId(), hospCheckCategory.getHospId());
            // 获取category下的所有的区域
            int categoryAreas = areaService.getCategoryAreas(hospCheckCategory.getCategoryId()).size();

            if(areaScores.size() != categoryAreas)
                throw new Exception();

            // 将所有的区域的分数都相加 => hospCheckCategory.score
            for(TbCheckAreaScore areaScore : areaScores)
                hospCheckCategory.setScore(hospCheckCategory.getScore().add(areaScore.getScore()));
            // 将hospCheckCategory的deleteFlag变成true
            hospCheckCategory.setDeleteFlag(true);
            if(!hospCheckCategoryService.updateById(hospCheckCategory))
                throw new Exception();

            // 查看所有的项目是否都完成
            if(hospCheckCategoryService.isBatchCategoryCompleted(hospCheckCategory.getBatchId())){
                TbCheckBatch batch = batchService.getById(hospCheckCategory.getBatchId());
                batch.setStatus("02");
                if(!batchService.updateById(batch))
                    throw new Exception();
            }


        }catch (Exception e){
            e.printStackTrace();
            return R.error(e.getMessage());
        }

        return R.ok();
    }

}
